<template>
  <div class="edit-book">
    <el-form ref="form"
             :model="form"
             labelWidth="80px">
      <el-form-item label="图书名称">
        <el-input v-model="form.xpk_1913040735_bookName"
                  placeholder="请输入图书名称" />
      </el-form-item>
      <el-form-item label="图书价格">
        <el-input v-model="form.xpk_1913040735_bookPrice"
                  placeholder="请输入图书价格" />
      </el-form-item>
      <el-form-item label="书籍类别">
        <el-select v-model="form.xpk_1913040735_bookType"
                   filterable
                   allowCreate
                   defaultFirstOption
                   placeholder="请选择书籍类别">
          <template v-for="(item, index) in filters">
            <el-option :key="index"
                       :label="item.xpk_1913040735_bookType"
                       :value="item.xpk_1913040735_bookType" />
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="书籍封面">
        <el-upload action="#"
                   listType="picture-card"
                   :limit="1"
                   :fileList="fileList"
                   :autoUpload="false"
                   :onChange="onChange">
          <i slot="default"
             class="el-icon-plus" />
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   @click="onSubmit">
          提交修改
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { addBookType, getBookTypes, updateBook, uploadImage } from '../api'
// , updateBook, uploadImage

export default {
  mounted () {
    if (process.env.NODE_ENV == 'development') {
      this.process = 'http://192.168.43.158:8088/'
    } else if (process.env.NODE_ENV == 'production') {
      this.process = 'http://39.105.201.210:8088/'
    }
    this.getTypes()
    const data = JSON.parse(sessionStorage.getItem('book_edit_data'))
    if (data) {
      this.form = data
      this.fileList = [{
        name: this.form.xpk_1913040735_bookPicture,
        url: this.process + this.form.xpk_1913040735_bookPicture
      }]
    }
    this.image_name = this.form.xpk_1913040735_bookPicture
  },
  watch: {
    form: {
      handler (newVal) {
        sessionStorage.setItem('book_edit_data', JSON.stringify(newVal))
      },
      deep: true
    },
    'form.xpk_1913040735_bookType': {
      handler (newVal) {
        console.log(this.filters)
        console.log(newVal)
        this.filters.find(item => {
          console.log(item)
          if (item.xpk_1913040735_bookType == newVal) {
            this.form.xpk_1913040735_bookTypeId = item.xpk_1913040735_bookTypeId
          }
        })
      }
    }
  },
  data () {
    return {
      form: {
        xpk_1913040735_bookName: '',
        xpk_1913040735_bookPrice: '',
        xpk_1913040735_bookType: '',
        xpk_1913040735_bookTypeId: '',
        xpk_1913040735_bookPicture: ''
      },
      filters: [],
      typeList: [],
      fileList: [],
      image_file: '',
      image_name: '',
      process: ''
    }
  },
  methods: {
    async onSubmit () {
      const data = this.form
      let typeId = ''
      const index = this.typeList.indexOf(data.xpk_1913040735_bookType)
      if (index > -1) {
        console.log('已有类别')
        typeId = this.filters[index].xpk_1913040735_bookTypeId
        console.log(typeId)
      } else {
        console.log('新建类别')
        await addBookType({ xpk_1913040735_bookType: data.xpk_1913040735_bookType }).then(res => {
          console.log(res)
          if (res) {
            typeId = res.xpk_1913040735_bookTypeId
            // console.log(typeId)
            this.getTypes()
          }
        })
      }
      console.log(this.form.xpk_1913040735_bookPicture)
      console.log(this.image_name)
      if (this.form.xpk_1913040735_bookPicture !== this.image_name) {
        console.log('改变')
        var formData = new FormData()
        console.log(this.image_file)
        formData.append('file', this.image_file)
        await uploadImage(formData).then(res => {
          console.log(res)
          if (typeof res === 'string') {
            console.log(res)
            const imgUrl = res
            const params = {
              xpk_1913040735_bookId: data.xpk_1913040735_bookId,
              xpk_1913040735_bookName: data.xpk_1913040735_bookName,
              xpk_1913040735_bookPrice: data.xpk_1913040735_bookPrice,
              xpk_1913040735_bookTypeId: typeId,
              xpk_1913040735_bookPicture: imgUrl
            }
            console.log(params)
            updateBook(params).then(res => {
              console.log(res)
              this.$message({
                showClose: true,
                message: '修改成功',
                type: 'success'
              })
              sessionStorage.removeItem('book_edit_data')
              this.$router.replace({ name: 'bookList' })
            })
          }
        })
      } else {
        console.log('未改变')
        const params = {
          xpk_1913040735_bookId: data.xpk_1913040735_bookId,
          xpk_1913040735_bookName: data.xpk_1913040735_bookName,
          xpk_1913040735_bookPrice: data.xpk_1913040735_bookPrice,
          xpk_1913040735_bookTypeId: typeId,
          xpk_1913040735_bookPicture: data.xpk_1913040735_bookPicture
        }
        console.log(params)
        updateBook(params).then(res => {
          console.log(res)
          this.$message({
            showClose: true,
            message: '修改成功',
            type: 'success'
          })
          sessionStorage.removeItem('book_edit_data')
          this.$router.replace({ name: 'bookList' })
        })
      }
    },
    onChange (file) {
      console.log(file)
      this.image_file = file.raw
      this.fileList = [{ name: file.name, url: file.url }]
      this.form.xpk_1913040735_bookPicture = 'img/' + file.name
      console.log(this.form.xpk_1913040735_bookPicture)
    },
    async getTypes () {
      await getBookTypes().then(res => {
      // console.log(res)
        this.filters = res
        this.typeList = this.filters.map(item => {
          return item.xpk_1913040735_bookType
        })
        console.log(this.typeList)
      })
    }
  }
}
</script>

<style lang="less" scoped>
@import '../assets/css/index.less';

.edit-book {
  margin: 16px 32px;
}
</style>
